package com.xx.jicheng.controller;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.yihang.common.spring.JsonModel;

import com.fasterxml.jackson.databind.ObjectMapper;

@ControllerAdvice
public class ExceptionController {

	private ObjectMapper mapper = new ObjectMapper();
	
	@ExceptionHandler(LoginException.class)
	@Order(1)
	public String handlerLogin(LoginException login){
		return "/login";
	}

	@ExceptionHandler
	@Order(Ordered.LOWEST_PRECEDENCE)
	public String handler(HttpServletRequest request, HttpServletResponse response, Throwable exp) {
		exp.printStackTrace();
		String xhr = request.getHeader("X-Requested-With");
		try {
			if (xhr != null && xhr.equals("XMLHttpRequest")) {
				JsonModel model = new JsonModel();
				model.add("success", false).add("message", exp.getMessage());
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				response.setCharacterEncoding("utf-8");
				response.setContentType("application/json");
				mapper.writeValue(response.getOutputStream(), model.asMap());
				return null;
			} else {				
				request.setAttribute("exception", exp);
				return "error";
			}
		} catch (Exception e) {
			request.setAttribute("exception", exp);
			return "error";
		}

	}

}
